mini.parse();

var table_click = '';
var form_click = '';
var arr = [];//表格按数据库表名分组
var arr_table = [];
var arr_form = [];
var datas = [];
// console.log(bootPATH,'bootPATH');

var formSh;
var action;
var formId;

var edit_data;//编辑的数据
var edit_form = [];//编辑的表单数据
var edit_table = [];//编辑的表格数据
var t_arr = [];//存放表格id

var formItem = parent.getFormItem();//菜单跳转后获取数据
console.log(formItem,'formItem');
if(formItem != []) {
    formId = formItem.formListId;
    action = 'add';
}else {
    // var formSh = $.parseJSON(document.cookie.substring(6));//获取add/edit数据
    formSh = localStorage.getItem("formShow");
    formSh = $.parseJSON(formSh);
    console.log(formSh,'formShow');
    action = formSh.action;
    formId = formSh.formListId;
}

$(function () {
    if(action == 'edit') {//编辑跳转
        // formId = formSh.formListId;
        edit_data = formSh.edit_data;
        console.log(edit_data,'edit_data');

    }else {
        //新增跳转
        // formId = formSh.formListId;
        edit_data = [];
    }

    formInit();

})

//初始化表单
function formInit(){
    //设置表格页的高度
    var height = $('.formTable').height() - $('.table-toolbar').height();
    $('#formGrid').css({
        height: height
    });
    // console.log(height,'height');
    // console.log(formId,'选择的表单id');
    var url =  ajaxUrl + "/formltems/findByFormListId.do";
    $.ajax({
        type : 'post',
        url : url,
        data : {
        	formId : formId
        },
        dataType : 'json',
        success : function (data) {
            datas = data['data'];
            showForm(data['data']);//渲染

            //编辑模式，赋值
            if(action == 'edit') {

                var formField = $("#formField").children();
                console.log(formField,'formField');
                for(var i = 0; i <formField.length; i++){
                    console.log(formField[i].id,'id');
                    if(formField[i].className == 'form_items') {

                        var form = new mini.Form("#"+formField[i].id);
                        form.setData(edit_data[formSh.cTableName][0], false);
                        edit_form = edit_data[formSh.cTableName][0];

                    }else {
                        var grid = mini.get(formField[i].id);
                        var e = edit_data[formField[i].id.substring(8)];
                        for(var k = 0; k <e.length; k++) {
                            e[k].cTableName = formField[i].id.substring(8);//加入子表名
                        }
                        grid.setData(edit_data[formField[i].id.substring(8)], false);
                        edit_table.push({
                            cTableName: formField[i].id.substring(8),
                            obj: edit_data[formField[i].id.substring(8)]
                        });
                    }
                }
            }
        },
        error : function (message) {
            // console.log(message);
        }
    })
}

//实例化表单、表格
function showForm(data) {
    console.log(data);
    arr_table = [];
    //表标题
    $("#formName").append("<h1 id='"+ data[0].cTableName +"'>"+ data[0].cFormName +"</h1>");
    for(var i = 0; i < data.length; i++){
        if(data[i].type == 'child') {
            //生成表格
            arr_table.push(data[i]);
        }else if(data[i].type == 'main') {
            //生成表单
            arr_form.push(data[i]);
            var id = data[i].cTableField;
            var type = data[i].cType;
            console.log(type,'type');
            // type= 'buttonedit';
            // type= 'upload';
            // type= 'textarea';
            // type= 'checkbox';
            // type= 'radio';
            // type= 'combobox';
            // type= 'datepicker';

            var form_items = '<div id="form'+ id + '" class="form_items" ' +
                'style="top:'+data[i].iConY+'px;left:'+data[i].iConX+'px">' +
                '<label id="label'+ id + '">'+ data[i].cLadText + ':</label>\n';

            if(type == 'radio') {
                form_items += '<input id="'+ id + '"  name="'+ id + '" type="'+ type + '" />' +
                    '</div>';
            }else if(type == 'upload') {
                form_items += '<input class="mini-htmlfile" name="'+ id + '"  id="'+ id + '"/>'+
                    '<input type="button" value="上传" onclick="ajaxFileUpload()"/></div>';
            }
            else{
                form_items += '<input id="'+ id + '"  name="'+ id + '" class="mini-'+ type + ' visibility" />' +
                    '</div>';
                //     mini.parse();
            }

            var style_label = {
                width: data[i].iWidth - data[i].iLabWidth,
                height: data[i].iLabHeight
            };
            var style_input = {
                width: data[i].iLabWidth,
                height: data[i].iLabHeight
            };
            //渲染到页面
            $("#formField").append(form_items);
            mini.parse();

            $('#form'+ id).css({
                width: data[i].iWidth + 100,
                height: data[i].iLabHeight
            });
            $('.form_items>span>span').css({
                height: '100%'
            });

            $('#label'+ id).css(style_label);
            $('#'+ id).css(style_input);
            mini.parse();

            $("#"+ id).click(function () {
                form_click = $(this).attr('id');
            })
            //增加点击事件
            if(type == 'buttonedit') {
                $("#"+ id).click(openBox);
            }
        }
    }
    //生成表格

    arr = jsonByGroup(arr_table);//表格按数据库表名分组

    for(var i = 0; i < arr.length; i++) {
        //每个arr[i]是一个表格
        var flag = '';
        // var type= 'buttonedit';
        // type= 'upload';
        // type= 'textarea';
        // type= 'checkbox';
        // type= 'radio';
        // type= 'combobox';
        // type= 'datepicker';

        var cols = [{ type: "checkcolumn" },{ type: "indexcolumn",header:'序号' }];
        for(var j = 0; j < arr[i].data.length; j++) {
            // console.log(arr[i].data[j]);//每一条表格数据
            var type = arr[i].data[j].cType;
            cols.push({
                field:arr[i].data[j].cTableField,
                // field:"name1",
                headerAlign: "center",
                allowSort: true,
                header: arr[i].data[j].cLadText,
                // editor: { type: arr[i].data[j].cType }
                editor: { type: type}
            })
            if(type == 'upload') {
                type = 'buttonedit';
                flag='upload';
            }else {
                flag='';
            }
            //添加弹出框类型点击事件
            if(cols[cols.length-1].editor.type == 'buttonedit' && flag == '') {
                cols[cols.length-1].editor.onbuttonclick = "onButtonEdit";
            }else if(cols[cols.length-1].editor.type == 'buttonedit' && flag == 'upload') {
                cols[cols.length-1].editor.onbuttonclick = "onUpload";
            }else if(cols[cols.length-1].editor.type == 'datepicker') {
                cols[cols.length-1].dateFormat = "yyyy-MM-dd";
            }else if(cols[cols.length-1].editor.type == 'checkbox') {
                cols[cols.length-1] = { type: "checkcolumn" };
            }
        }
        console.log(cols,'cols');

        var grid = new mini.DataGrid();//js创建表格
        grid.set({
            url: "",
            // style: "",
            id:"datagrid"+arr[i].cTableName,
            columns: cols,
            multiSelect:true,
            allowResize:true,
            allowCellEdit:true,
            allowCellSelect:true,
            // cellEditAction: "cellclick",
            allowRowSelect: true,
            showPager:false,
            editNextOnEnterKey:true,
            editNextRowCell:true
        });
        grid.render(document.getElementById("formField"));
        t_arr.push("datagrid"+arr[i].cTableName);
        $("#datagrid"+arr[i].cTableName).css({
            width: arr[i].iWidth,
            height: arr[i].iLabHeight,
            "min-height": 150,
            top: arr[i].iConY,
            left: arr[i].iConX
        });
        var data = [{}];
        grid.setData(data);
        $("#datagrid"+arr[i].cTableName).click(function () {
            // console.log($(this).attr('id'))
            table_click = $(this).attr('id');
            //回车增加一行
            addRow();
        })
    }
}

//保存
function save(){
    console.log(arr_form,'arr_form');
    console.log(arr_table,'arr_table');
    var form_data = getForm();
    var form = [];

    for(item in form_data){
        console.log(item);
        for(var i = 0;i<arr_form.length;i++) {
            if(arr_form[i].cTableField == item) {
                form.push({
                    cTableName:arr_form[i].cTableName,
                })
                form[form.length-1][item] = form_data[item]
            }
        }
    }
    // for(var j = 0;j<form_data.length;j++) {
    //     if(arr_form[i].cTableField == form_data[j].cTableField) {
    //         form_data[j].cTableName = arr_form[i].cTableName;
    //     }
    // }
    console.log(form,'');

    //转换表单数据成为所需数据格式
    form = FormByGroup(form);
    form[0].type = 'main';
    var time = new Date().getTime();
    form[0].obj.id = time;
    console.log(form,'form');

    var table_data = [];
    for(var i = 0;i<arr.length;i++) {
        var grid = mini.get("datagrid"+arr[i].cTableName);
        for(var j = 0;j<grid.getData().length;j++) {
            grid.getData()[j].cTableName = arr[i].cTableName;
            table_data.push(grid.getData()[j]);
        }
    }
    //转换表格数据成为所需数据格式

    for(var i = 0;i<table_data.length;i++) {
        // delete table_data[i]._id;
        // delete table_data[i]._uid;
        // delete table_data[i]._state;
        table_data[i].obj = {};
        table_data[i].type = 'child';
        for(var item in table_data[i]) {
            if(item != 'cTableName'&& item != 'obj'&& item != 'type') {
                table_data[i].obj[item] = table_data[i][item];
                // delete table_data[i][item];
            }
        }
    }
    console.log(table_data,'table_data');

    //合并
    for(var i = 0;i<table_data.length;i++) {
        form.push(table_data[i]);
    }
    for(var i = 0;i<form.length;i++) {
        form[i].obj.formId = formId;
        if(form[i].type == 'child') {
            form[i].obj.id = new Date().getTime() + i*100;
            form[i].obj.mTableId = time;
        }
    }

    for(var i=0;i< form.length;i++) {
        for (var item in form[i].obj) {
            if (item == '_id' || item == '_uid' ||item == '_state') {
                delete form[i].obj[item];
            }
        }
    }

    var url;
    if(action == 'edit') {
        console.log(edit_form,'edit_form');
        console.log(edit_table,'edit_table');
        url = ajaxUrl + "/formltems/formDbSource.do";
        for(var i=0;i< form.length;i++) {
            if(form[i].type == 'main') {
                form[i].obj.id = edit_form.id;
                form[i].formId = formId;
            }else {
                form[i].obj.mTableId = edit_form.id;
                form[i].mTableId = edit_form.id;
                form[i].formId = formId;
            }
        }
    }else {
        url = ajaxUrl + "/dbsource/dbInsert.do";
    }
    console.log(form);

    form = JSON.stringify(form);
    console.log(form);

    $.ajax({
        type : 'post',
        url : url,
        dataType : 'json',
        data : form,
        contentType: 'application/json',
        success : function (data) {
            console.log(data);
            //mini.alert('保存成功！');
            console.log(t_arr,'表格id');

            // parent.removeTab();//保存成功，关闭页面

        },
        error : function () {
            alert('保存失败');
        }
    })
}

//表单弹出框
function openBox() {
    // console.log($(this));
    var id = $(this).attr('id');
    console.log(id);
    var reference = {};
    for(var i=0;i<datas.length;i++) {
        if(datas[i].cTableField == id) {
            var json = $.parseJSON(datas[i].cRefObj);
            reference = json.reference;
        }
    }
    console.log(reference,'reference');
    mini.open({
        url: bootPATH + "../frame/frame1/pages/formLayout/openBox.html",
        title: "参照",
        onload: function () {
            var iframe = this.getIFrameEl();
            var data = {
                reference: reference
            };
            iframe.contentWindow.SetData(data);
        },
        ondestroy: function (action) {//关闭之前执行
            // if (action == "close") return false;
            // alert(1);
            // console.log(action);
            if (action == "ok") {
                var iframe = this.getIFrameEl();
                var data = iframe.contentWindow.onTableOk();
                data = mini.clone(data);
                console.log(data);
                // $("#"+id).attr("value", data[0].name);
                var t = mini.get(id);
                t.setValue(data[0]['test_table_code']);
                t.setText(data[0]['test_table_code']);
            }
        }
    });
}

// 表格弹窗
function onButtonEdit(e) {
    // var btnEdit1 = e.sender;
    // console.log(btnEdit1,'sender');

    console.log($(this),'');
    console.log(table_click,'table_click');//所属表格id
    mini.open({
        url: bootPATH + "../frame/frame1/pages/formLayout/openBox.html",
        title: "参照",
        onload: function () {
            // var iframe = this.getIFrameEl();
            // var data = {
            //      id: id
            // };
            // iframe.contentWindow.SetData(data);
        },
        ondestroy: function (action) {//关闭之前执行
            if (action == "ok") {
                var iframe = this.getIFrameEl();
                var data = iframe.contentWindow.onTableOk();
                data = mini.clone(data);
                console.log(data,'data');

                //设置弹窗选择后的值
                var dept_grid = mini.get(table_click);
                dept_grid.cancelEdit();
                var row = dept_grid.getSelected();
                console.log(row,'row');
                var row2 = dept_grid.getCurrentCell();
                var field = row2[1].field;
                console.log(row2,'row2');
                console.log(field,'field');
                dept_grid.updateRow(row, data[0]);
                // dept_grid.updateRow(row[field],data[0][field]);
                // dept_grid.on("drawcell",function (e) {
                //     console.log(e,'e');
                //     console.log(dept_grid.getCellEl(),'dept_grid.getCellEl()');
                // });

            }
        }
    });
}

//对象数组分组
function jsonByGroup(arr_table) {
    // console.log(arr_table);
    var map = {},
        dest = [];
    for(var i = 0; i < arr_table.length; i++){
        var ai = arr_table[i];
        if(!map[ai.cTableName]){
            dest.push({
                cTableName: ai.cTableName,
                id: ai.id,
                data: [ai],
                iConX: ai.iConX,
                iConY: ai.iConY,
                iLabHeight: ai.iLabHeight,
                iLabWidth: ai.iLabWidth,
                iWidth: ai.iWidth
            });
            map[ai.cTableName] = ai;
        }else{
            for(var j = 0; j < dest.length; j++){
                var dj = dest[j];
                if(dj.cTableName == ai.cTableName){
                    dj.data.push(ai);
                    break;
                }
            }
        }
    }

    console.log(dest,'分组后');
    return dest;
}

//表单最终数据分组
function FormByGroup(form) {
    // console.log(arr_table);
    var map = {},
        dest = [];
    for(var i = 0; i < form.length; i++){
        var ai = form[i];
        if(!map[ai.cTableName]){
            dest.push({
                cTableName: ai.cTableName,
                obj: {}
            });
            map[ai.cTableName] = ai;
        }
            for(var j = 0; j < dest.length; j++){
                var dj = dest[j];
                if(dj.cTableName == ai.cTableName){
                    // for(var i = 0; i < ai.length; i++){
                    //
                    // }
                    for(k in ai){
                        dj.obj[k] = ai[k]
                    }
                    delete dj.obj.cTableName;
                    // dj.obj.push(ai);
                    break;
                }
            }

    }

    console.log(dest,'分组后');
    return dest;
}
//表格回车时添加一行
function addRow() {
    // console.log(table_click);
    var dept_grid = mini.get(table_click);
    dept_grid.on("celleditenter", function (e) {
        // console.log(dept_grid,'回车事件');
        var index = dept_grid.indexOf(e.record);
        if (index == dept_grid.getData().length - 1) {
            var row = {};
            dept_grid.addRow(row);
        }
    });
}
//表格删除行
function removeRow() {
    var grid = mini.get(table_click);
    var rows = grid.getSelecteds();
    var data = grid.getData();
    if (rows.length > 0 && data.length > 1) {
        grid.removeRows(rows, true);
        console.log(rows,'del rows');
        var del_data = [];
        for(var i=0;i<rows.length;i++) {
            if(rows[i]._state != 'added') {
                del_data.push({
                    id: rows[i].id,
                    cTableName: rows[i].cTableName
                });
            }
            // }else {
            //
            // }
        }
        console.log(del_data,'del_data');
        del_data = JSON.stringify(del_data)
        $.ajax({
            type : 'post',
            url : ajaxUrl + '/dbsource/dbDelete.do',
            dataType : 'json',
            data : del_data,
            contentType: 'application/json',
            success : function (data) {
                console.log(data);
            },
            error : function () {
                // alert('删除失败');
            }
        })
    }
}

//表单文件上传
function ajaxFileUpload() {
    var inputFile = $("#file1 > input:file")[0];
    // console.log(inputFile,'inputFile');
    $.ajaxFileUpload({
        url: 'upload.aspx',                 //用于文件上传的服务器端请求地址
        fileElementId: inputFile,               //文件上传域的ID
        //data: { a: 1, b: true },            //附加的额外参数
        dataType: 'text',                   //返回值类型 一般设置为json
        success: function (data, status)    //服务器成功响应处理函数
        {
            alert("上传成功: " + data);
        },
        error: function (data, status, e)   //服务器响应失败处理函数
        {
            alert(e);
        },
        complete: function () {
            var jq = $("#file1 > input:file");
            jq.before(inputFile);
            jq.remove();
        }
    });
}

// 表格上传文件弹窗
function onUpload(e) {

    console.log($(this),'');
    console.log(table_click,'table_click');//所属表格id
    mini.open({
        url: bootPATH + "../frame/frame1/pages/formLayout/openUpload.html",
        title: "上传",
        height: 200,
        width: 400,
        onload: function () {

        },
        ondestroy: function (action) {//关闭之前执行
            if (action == "ok") {
                var iframe = this.getIFrameEl();
                var data = iframe.contentWindow.onTableOk();
                data = mini.clone(data);
                console.log(data,'data');

                //设置弹窗选择后的值
                var dept_grid = mini.get(table_click);
                dept_grid.cancelEdit();
                var row = dept_grid.getSelected();
                console.log(row,'row');
                var row2 = dept_grid.getCurrentCell();
                var field = row2[1].field;
                console.log(row2,'row2');
                console.log(field,'field');
                var row_data = {};
                row_data[field] = data;
                // dept_grid.updateRow(row, data[0]);
                dept_grid.updateRow(row,row_data);
            }
        }
    });
}

//表单操作
function getForm() {
    var form = new mini.Form("#formField");
    var data = form.getData(true, false);
    // var s = mini.encode(data);
    console.log(data);
    return data;
    // alert(s);
    //form.setIsValid(false);
}
function setForm(obj) {
    var form = new mini.Form("#formField");
    form.setData(obj, false);
}
function resetForm() {
    var form = new mini.Form("#formField");
    form.reset();
}
function clearForm() {
    var form = new mini.Form("#formField");
    form.clear();
}


